//
//  RegisteViewController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/10/27.
//

#import "RegisteViewController.h"

@interface RegisteViewController ()<UITextViewDelegate>

@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *psdTF;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) UIButton *eyeBtn;
@property (nonatomic, strong) UIButton *confirmBtn;

@end

@implementation RegisteViewController

- (void)initDidLoad {
    self.navigationTitle = self.type == 1 ? @"忘记密码" : @"注册";
    self.hbd_barAlpha = 0;
}

- (void)initViews {
    UIImageView *bgimageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bglogin"]];
    bgimageV.contentMode = UIViewContentModeScaleAspectFill;
    bgimageV.clipsToBounds = YES;
    [self.view addSubview:bgimageV];
    
    [bgimageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    UIView *phoneBg = [[UIView alloc] init];
    phoneBg.backgroundColor = kRGB(0xF7F7F7FF);
    phoneBg.layer.cornerRadius = 25;
    phoneBg.layer.masksToBounds = YES;
    [self.view addSubview:phoneBg];
    
    [phoneBg addSubview:self.phoneTF];
    
    UIView *psdBg = [[UIView alloc] init];
    psdBg.backgroundColor = kRGB(0xF7F7F7FF);
    psdBg.layer.cornerRadius = 25;
    psdBg.layer.masksToBounds = YES;
    [self.view addSubview:psdBg];
    
    [psdBg addSubview:self.psdTF];
    [psdBg addSubview:self.eyeBtn];
    
    UIView *codeBg = [[UIView alloc] init];
    codeBg.backgroundColor = kRGB(0xF7F7F7FF);
    codeBg.layer.cornerRadius = 25;
    codeBg.layer.masksToBounds = YES;
    [self.view addSubview:codeBg];
    
    [codeBg addSubview:self.codeTF];
    [codeBg addSubview:self.codeBtn];
    
    [self.view addSubview:self.confirmBtn];
    
    NSString *text = @"注册即代表您同意 <用户协议> 和 <隐私政策>";
    NSMutableParagraphStyle *muParagraph = [[NSMutableParagraphStyle alloc] init];
    muParagraph.lineSpacing = 10;
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange range1 = [text rangeOfString:@"<用户协议>"];
    NSRange range2 = [text rangeOfString:@"<隐私政策>"];
    
    [attrStr addAttributes:@{NSForegroundColorAttributeName:kBgColor} range:range1];
    [attrStr addAttributes:@{NSForegroundColorAttributeName:kBgColor} range:range2];
    [attrStr addAttribute:NSLinkAttributeName value:@"terms://" range:range1];
    [attrStr addAttribute:NSLinkAttributeName value:@"privacy://" range:range2];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(40, kHeightForScreen-30-kHeightForTabbarExtra-15, kWidthForScreen-80, 30)];
    textView.editable = NO;
    textView.scrollEnabled = NO;
    textView.delegate = self;
    textView.attributedText = attrStr;
    textView.textAlignment = NSTextAlignmentCenter;
    textView.font = kFontBold(10);
    textView.textColor = [UIColor blackColor];
    textView.backgroundColor = [UIColor clearColor];
    textView.linkTextAttributes = @{NSForegroundColorAttributeName:kBgColor};
    [self.view addSubview:textView];
    
    [phoneBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(40);
        make.trailing.mas_equalTo(-40);
        make.top.mas_equalTo(100+kHeightForNaigation);
        make.height.mas_equalTo(50);
    }];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 20, 0, 20));
    }];
    [codeBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(phoneBg);
        make.top.mas_equalTo(phoneBg.mas_bottom).offset(20);
    }];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 20, 0, 150));
    }];
    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(-20);
        make.centerY.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(110, 20));
    }];
    [psdBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.equalTo(phoneBg);
        make.top.mas_equalTo(codeBg.mas_bottom).offset(20);
    }];
    [self.psdTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 20, 0, 50));
    }];
    [self.eyeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.trailing.mas_equalTo(0);
        make.width.height.mas_equalTo(50);
    }];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(290, 50));
        make.top.mas_equalTo(psdBg.mas_bottom).offset(100);
    }];
}

#pragma mark - action
- (void)confirmAction {
    if (self.phoneTF.text.length <= 0) {
        kShowText(@"请输入手机号");
        return;
    }
    if (self.psdTF.text.length <= 0) {
        kShowText(@"请输入密码");
        return;
    }
    [YPProgressHud showHudInview:self.view];
    if (self.type == 1) {
        [NET resetPasswordWithPhone:self.phoneTF.text code:self.codeTF.text psd:self.psdTF.text success:^(id  _Nonnull responseObject) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(@"密码已充值,请重新登录");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(error.userInfo[kHttpErrorReason]);
        }];
    }else {
        [NET registeWithPhone:self.phoneTF.text code:self.codeTF.text psd:self.psdTF.text success:^(id  _Nonnull responseObject) {
            UserModel *model = [UserModel mj_objectWithKeyValues:responseObject];
            kUserAccount.user = model;
            [kUserAccount setRootController];
            [YPProgressHud hideHudForView:self.view];
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(error.userInfo[kHttpErrorReason]);
        }];
    }
    
}

/// 验证码
- (void)codeAction {
    if (self.phoneTF.text.length <= 0) {
        kShowText(@"请输入手机号");
        return;
    }
    [YPProgressHud showHudInview:self.view];
    if (self.type == 1) {
        [NET sendResetPsdCode:self.phoneTF.text success:^(id  _Nonnull responseObject) {
            [YPProgressHud hideHudForView:self.view];
            [self timeCountDownAction];
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(error.userInfo[kHttpErrorReason]);
        }];
    }else {
        [NET sendCode:self.phoneTF.text success:^(id  _Nonnull responseObject) {
            [YPProgressHud hideHudForView:self.view];
            [self timeCountDownAction];
        } failure:^(NSError * _Nonnull error) {
            [YPProgressHud hideHudForView:self.view];
            kShowText(error.userInfo[kHttpErrorReason]);
        }];
    }
}


- (void)timeCountDownAction {
    __block int duration = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (duration <= 1) {
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:kBgColor forState:UIControlStateNormal];
                self.codeBtn.enabled = YES;
                dispatch_source_cancel(timer);
            }else {
                duration--;
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%ds后重新获取",duration] forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:kRGB(0x999999) forState:UIControlStateNormal];
                self.codeBtn.enabled = NO;
            }
        });
    });
    dispatch_resume(timer);
}

#pragma mark - 懒加载
- (UITextField *)phoneTF {
    if (!_phoneTF) {
        _phoneTF = [[UITextField alloc] initWithFrame:CGRectZero];
        _phoneTF.textColor = [UIColor blackColor];
        _phoneTF.borderStyle = UITextBorderStyleNone;
        _phoneTF.placeholder = @"请输入您的手机号";
        _phoneTF.keyboardType = UIKeyboardTypePhonePad;
        _phoneTF.font = kFontRegula(14);
    }
    return _phoneTF;
}
- (UITextField *)psdTF {
    if (!_psdTF) {
        _psdTF = [[UITextField alloc] initWithFrame:CGRectZero];
        _psdTF.textColor = [UIColor blackColor];
        _psdTF.borderStyle = UITextBorderStyleNone;
        _psdTF.placeholder = @"请输入您的密码";
        _psdTF.keyboardType = UIKeyboardTypeASCIICapable;
        _psdTF.secureTextEntry = YES;
        _psdTF.font = kFontRegula(14);
    }
    return _psdTF;
}
- (UIButton *)eyeBtn {
    if (!_eyeBtn) {
        _eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_eyeBtn setImage:[UIImage imageNamed:@"yanjing"] forState:UIControlStateNormal];
        [_eyeBtn setImage:[UIImage imageNamed:@"yanjing-3"] forState:UIControlStateSelected];
        _eyeBtn.selected = YES;
        @weakify(self)
        [[_eyeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self)
            self.eyeBtn.selected = !self.eyeBtn.selected;
            self.psdTF.secureTextEntry = self.eyeBtn.selected;
        }];
    }
    return _eyeBtn;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmBtn.backgroundColor = kBgColor;
        _confirmBtn.layer.cornerRadius = 25;
        _confirmBtn.layer.masksToBounds = YES;
        [_confirmBtn setTitle:self.type == 1 ? @"确认" : @"注册并登录" forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = kFontCarter(18);
        @weakify(self)
        [[_confirmBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self)
            [self confirmAction];
        }];
    }
    return _confirmBtn;
}

- (UITextField *)codeTF {
    if (!_codeTF) {
        _codeTF = [[UITextField alloc] initWithFrame:CGRectZero];
        _codeTF.textColor = [UIColor blackColor];
        _codeTF.borderStyle = UITextBorderStyleNone;
        _codeTF.placeholder = @"请输入验证码";
        _codeTF.keyboardType = UIKeyboardTypeNumberPad;
        _codeTF.font = kFontRegula(14);
        @weakify(self)
        [_codeTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
         @strongify(self)
            if (x.length > 6) {
                self.codeTF.text = [x substringToIndex:6];
            }
        }];
    }
    return _codeTF;
}
- (UIButton *)codeBtn {
    if (!_codeBtn) {
        _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_codeBtn setTitleColor:kBgColor forState:UIControlStateNormal];
        _codeBtn.titleLabel.font = kFontRegula(14);
        _codeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        @weakify(self)
        [[_codeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self)
            [self codeAction];
        }];
    }
    return _codeBtn;
}


#pragma mark - delegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
    if ([[URL scheme] isEqualToString:@"terms"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://static.456465465465465.top/services/UserAgreement.html"] options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@(YES)} completionHandler:^(BOOL success) {
        }];
        return NO;
    }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://static.456465465465465.top/services/PrivacyPolicy.html"] options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@(YES)} completionHandler:^(BOOL success) {
        }];
        return NO;
    }
    return YES;
}

@end
